// Initial Page
document.getElementById('registerButton').addEventListener('click', () => {
  document.getElementById('initialPage').style.display = 'none';
  document.getElementById('registerForm').style.display = 'block';
});

document.getElementById('loginButton').addEventListener('click', () => {
  document.getElementById('initialPage').style.display = 'none';
  document.getElementById('loginForm').style.display = 'block';
});

// Registration Form
document.getElementById('register').addEventListener('submit', async (e) => {
  e.preventDefault();
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
  const name = document.getElementById('name').value;
  const contact = document.getElementById('contact').value;

  const response = await fetch('/users/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password, name, contact })
  });

  if (response.ok) {
    const data = await response.json();
    document.getElementById('registerMessage').innerText = 'Registration successful!';
    document.getElementById('registerMessage').className = 'success';
    document.getElementById('registerForm').style.display = 'none';
    document.getElementById('loginForm').style.display = 'block';
  } else {
    const errorText = await response.text();
    document.getElementById('registerMessage').innerText = 'Registration failed: ' + errorText;
    document.getElementById('registerMessage').className = 'error';
  }
});

// Login Form
document.getElementById('login').addEventListener('submit', async (e) => {
  e.preventDefault();
  const username = document.getElementById('loginUsername').value;
  const password = document.getElementById('loginPassword').value;

  const response = await fetch('/users/login', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  });

  if (response.ok) {
    const data = await response.json();
    localStorage.setItem('token', data.token);

    // Fetch user details to get virtual currency balance
    const userResponse = await fetch('/users/profile', {
      headers: { 'Authorization': data.token }
    });

    if (userResponse.ok) {
      const userData = await userResponse.json();
      alert(`Login successful! Your balance: ${userData.virtual_currency}`);
    }

    document.getElementById('loginMessage').innerText = 'Login successful!';
    document.getElementById('loginMessage').className = 'success';
    document.getElementById('loginForm').style.display = 'none';
    document.getElementById('dashboard').style.display = 'block';
  } else {
    const errorText = await response.text();
    document.getElementById('loginMessage').innerText = 'Login failed: ' + errorText;
    document.getElementById('loginMessage').className = 'error';
  }
});
// Top-up Button
document.getElementById('topUpButton').addEventListener('click', () => {
  document.getElementById('dashboard').style.display = 'none';
  document.getElementById('topUpForm').style.display = 'block';
});

// Top-up Form Submission
document.getElementById('topUp').addEventListener('submit', async (e) => {
  e.preventDefault();
  const amount = document.getElementById('topUpAmount').value;

  const token = localStorage.getItem('token');
  const response = await fetch('/users/top-up', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    body: JSON.stringify({ amount })
  });

  if (response.ok) {
    const data = await response.json();
    document.getElementById('topUpMessage').innerText = `Top-up successful! New balance: ${data.balance}`;
    document.getElementById('topUpMessage').className = 'success';
  } else {
    const errorText = await response.text();
    document.getElementById('topUpMessage').innerText = 'Top-up failed: ' + errorText;
    document.getElementById('topUpMessage').className = 'error';
  }
});
// Dashboard
document.getElementById('manageItemsButton').addEventListener('click', () => {
  document.getElementById('dashboard').style.display = 'none';
  document.getElementById('itemManagement').style.display = 'block';
  loadItems();
});

document.getElementById('cartButton').addEventListener('click', () => {
  document.getElementById('dashboard').style.display = 'none';
  document.getElementById('cart').style.display = 'block';
  loadCart();
});

document.getElementById('ordersButton').addEventListener('click', () => {
  document.getElementById('dashboard').style.display = 'none';
  document.getElementById('orders').style.display = 'block';
  loadOrders();
});

document.getElementById('backToOrdersButton').addEventListener('click', () => {
  document.getElementById('orderDetails').style.display = 'none';
  document.getElementById('orders').style.display = 'block';
});

// Item Management
document.getElementById('addItem').addEventListener('submit', async (e) => {
  e.preventDefault();
  const productName = document.getElementById('productName').value;
  const productDescription = document.getElementById('productDescription').value;
  const productPrice = document.getElementById('productPrice').value;

  const token = localStorage.getItem('token');
  const response = await fetch('/items', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    body: JSON.stringify({ product_name: productName, product_description: productDescription, product_price: productPrice })
  });

  if (response.ok) {
    alert('Item added successfully!');
    loadItems();
  } else {
    const errorText = await response.text();
    alert('Failed to add item: ' + errorText);
  }
});

// Load Items
async function loadItems() {
  const token = localStorage.getItem('token');
  const response = await fetch('/items', {
    headers: { 'Authorization': token }
  });

  if (response.ok) {
    const items = await response.json();
    const itemsList = document.getElementById('itemsList');
    itemsList.innerHTML = '';
    items.forEach(item => {
      const itemDiv = document.createElement('div');
      itemDiv.className = 'item';
      itemDiv.innerHTML = `
        <h3>${item.product_name}</h3>
        <p>${item.product_description}</p>
        <p>Price: ${item.product_price}</p>
        <p>Owner: ${item.owner_name}</p>
        <p>Contact: ${item.owner_contact}</p>
        <div class="item-actions">
          <button onclick="editItem(${item.item_id})">Edit</button>
          <button onclick="deleteItem(${item.item_id})">Delete</button>
        </div>
        <button onclick="addToCart(${item.item_id},${item.product_price})">Add to Cart</button>
      `;
      itemsList.appendChild(itemDiv);
    });
  } else {
    const errorText = await response.text();
    alert('Failed to load items: ' + errorText);
  }
}

// Edit Item
async function editItem(itemId) {
  const token = localStorage.getItem('token');
  const response = await fetch(`/items/${itemId}`, {
    method: 'GET',
    headers: { 'Authorization': token }
  });

  if (response.ok) {
    const item = await response.json();
    const newItemName = prompt('Enter new item name:', item.product_name);
    const newItemDescription = prompt('Enter new item description:', item.product_description);
    const newItemPrice = prompt('Enter new item price:', item.product_price);

    const updateResponse = await fetch(`/items/${itemId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json', 'Authorization': token },
      body: JSON.stringify({
        product_name: newItemName,
        product_description: newItemDescription,
        product_price: newItemPrice
      })
    });

    if (updateResponse.ok) {
      alert('Item updated successfully!');
      loadItems();
    } else {
      const errorText = await updateResponse.text();
      alert('Failed to update item: ' + errorText);
    }
  } else {
    const errorText = await response.text();
    alert('Failed to fetch item: ' + errorText);
  }
}

// Delete Item
async function deleteItem(itemId) {
  const token = localStorage.getItem('token');
  const response = await fetch(`/items/${itemId}`, {
    method: 'DELETE',
    headers: { 'Authorization': token }
  });

  if (response.ok) {
    alert('Item deleted successfully!');
    loadItems();
  } else {
    const errorText = await response.text();
    alert('Failed to delete item: ' + errorText);
  }
}

// Add to Cart
async function addToCart(itemId, price) {
  const token = localStorage.getItem('token');
  const quantity = prompt('Enter quantity:', 1);
  
  if (quantity <= 0) {
    alert('Quantity must be greater than 0');
    return;
  }
  // 打印 itemId 和 quantity，确保它们是正确的
  console.log('itemId:', itemId);
  console.log('quantity:', quantity);
  
  const subtotal = price * quantity;
  const response = await fetch('/cart', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    body: JSON.stringify({ item_id: itemId, quantity, subtotal })
  });

  if (response.ok) {
    alert('Item added to cart successfully!');
    loadCart();
  } else {
    const errorText = await response.text();
    alert('Failed to add item to cart: ' + errorText);
  }
}

// Load Cart
async function loadCart() {
  const token = localStorage.getItem('token');
  const response = await fetch('/cart', {
    headers: { 'Authorization': token }
  });

  if (response.ok) {
    const cartItems = await response.json();
    const cartItemsDiv = document.getElementById('cartItems');
    const cartSummaryDiv = document.getElementById('cartSummary');
    
    cartItemsDiv.innerHTML = '';
    cartSummaryDiv.innerHTML = '';
    
    if (cartItems.length === 0) {
      cartItemsDiv.innerHTML = '<p>Your cart is empty</p>';
      document.getElementById('checkoutButton').style.display = 'none';
      return;
    }
    
    let totalAmount = 0;
    
    cartItems.forEach(item => {
      const itemDiv = document.createElement('div');
      itemDiv.className = 'item';
      itemDiv.innerHTML = `
        <h3>${item.product_name}</h3>
        <p>Price: ${item.product_price}</p>
        <p>Quantity: ${item.quantity}</p>
        <p>Subtotal: ${item.subtotal}</p>
        <button onclick="updateCartItem(${item.cart_id},${item.quantity + 1},${item.product_price})">Increase Quantity</button>
        <button onclick="updateCartItem(${item.cart_id},${item.quantity - 1},${item.product_price})">Decrease Quantity</button>
        <button onclick="removeFromCart(${item.cart_id})">Remove</button>
      `;
      cartItemsDiv.appendChild(itemDiv);
      
      totalAmount += item.subtotal;
    });
    
    cartSummaryDiv.innerHTML = `
      <h3>Cart Summary</h3>
      <p>Total Amount: ${totalAmount}</p>
    `;
    
    document.getElementById('checkoutButton').style.display = 'block';
    document.getElementById('checkoutButton').onclick = () => checkout(totalAmount);
  } else {
    const errorText = await response.text();
    alert('Failed to load cart: ' + errorText);
  }
}

// Update Cart Item
async function updateCartItem(cartId, quantity, price) {
  if (quantity <= 0) {
    removeFromCart(cartId);
    return;
  }
  
  const subtotal = price * quantity;
  const token = localStorage.getItem('token');
  const response = await fetch(`/cart/${cartId}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': token
    },
    body: JSON.stringify({ quantity, subtotal })
  });

  if (response.ok) {
    loadCart();
  } else {
    const errorText = await response.text();
    alert('Failed to update cart item: ' + errorText);
  }
}

// Remove from Cart
async function removeFromCart(cartId) {
  const token = localStorage.getItem('token');
  const response = await fetch(`/cart/${cartId}`, {
    method: 'DELETE',
    headers: { 'Authorization': token }
  });

  if (response.ok) {
    loadCart();
  } else {
    const errorText = await response.text();
    alert('Failed to remove item from cart: ' + errorText);
  }
}

async function checkout(totalAmount) {
  const token = localStorage.getItem('token');

  try {
    const response = await fetch('/orders', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': token
      },
      body: JSON.stringify({ totalAmount })
    });

    if (response.ok) {
      const data = await response.json();
      alert('Order created successfully with virtual currency!');
      window.location.href = 'payment-success.html';
    } else {
      const errorText = await response.text();
      alert('Failed to create order: ' + errorText);
    }
  } catch (error) {
    console.error('Checkout error:', error);
    alert('Checkout failed: ' + error.message);
  }
}



// Load Orders
async function loadOrders() {
  const token = localStorage.getItem('token');
  const response = await fetch('/orders', {
    headers: { 'Authorization': token }
  });

  if (response.ok) {
    const orders = await response.json();
    const ordersList = document.getElementById('ordersList');
    ordersList.innerHTML = '';
    
    if (orders.length === 0) {
      ordersList.innerHTML = '<p>You have no orders</p>';
      return;
    }
    
    orders.forEach(order => {
      const orderDiv = document.createElement('div');
      orderDiv.className = 'item';
      orderDiv.innerHTML = `
        <h3>Order #${order.order_id}</h3>
        <p>Total Amount: ${order.total_amount}</p>
        <p>Status: ${order.order_status}</p>
        <button onclick="viewOrderDetails(${order.order_id})">View Details</button>
        ${order.order_status === 'pending' ? '<button onclick="cancelOrder(${order.order_id})">Cancel</button>' : ''}
      `;
      ordersList.appendChild(orderDiv);
    });
  } else {
    const errorText = await response.text();
    alert('Failed to load orders: ' + errorText);
  }
}

// View Order Details
async function viewOrderDetails(orderId) {
  document.getElementById('orders').style.display = 'none';
  document.getElementById('orderDetails').style.display = 'block';
  
  const token = localStorage.getItem('token');
  const response = await fetch(`/orders/${orderId}`, {
    headers: { 'Authorization': token }
  });

  if (response.ok) {
    const order = await response.json();
    const detailsResponse = await fetch(`/orders/${orderId}/details`, {
      headers: { 'Authorization': token }
    });
    
    if (detailsResponse.ok) {
      const details = await detailsResponse.json();
      
      document.getElementById('orderInfo').innerHTML = `
        <h3>Order #${order.order_id}</h3>
        <p>Total Amount: ${order.total_amount}</p>
        <p>Status: ${order.order_status}</p>
        <p>Date: ${new Date(order.created_at).toLocaleDateString()}</p>
      `;
      
      const orderItemsDiv = document.getElementById('orderItems');
      orderItemsDiv.innerHTML = '';
      
      details.forEach(detail => {
        const itemDiv = document.createElement('div');
        itemDiv.className = 'item';
        itemDiv.innerHTML = `
          <h4>${detail.product_name}</h4>
          <p>Quantity: ${detail.quantity}</p>
          <p>Price: ${detail.price}</p>
        `;
        orderItemsDiv.appendChild(itemDiv);
      });
    }
  } else {
    const errorText = await response.text();
    alert('Failed to load order details: ' + errorText);
  }
}

// Cancel Order
async function cancelOrder(orderId) {
  const token = localStorage.getItem('token');
  const response = await fetch(`/orders/cancel/${orderId}`, {
    method: 'POST',
    headers: { 'Authorization': token }
  });

  if (response.ok) {
    alert('Order cancelled successfully!');
    loadOrders();
  } else {
    const errorText = await response.text();
    alert('Failed to cancel order: ' + errorText);
  }
}